package cn.easybuy.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.easybuy.dao.BaseDao;
import cn.easybuy.dao.UserDao;
import cn.easybuy.entity.User;

public class UserDaoImpl extends BaseDao implements UserDao{

	@Override
	public int saveUser(User user) {
		String sql="insert into easybuy_user(loginName,userName,password,sex,identityCode,email,mobile,type) values(?,?,?,?,?,?,?,?)";
		Object[] objects={user.getLoginName(),user.getUserName(),user.getPassword(),user.getSex(),user.getIdentityCode(),user.getEmail(),user.getMobile(),user.getType()};
		int num=this.executeUpdate(sql, objects);
		return num;
	}

	@Override
	public List<User> getUsersByLoginName(String loginName) { //验证注册登录名是否重复
		String sql="select userName from easybuy_user where loginName=?";
		ResultSet rs=this.exxcuteQuery(sql, loginName);
		List<User> list=new ArrayList<User>();
		try {
			while (rs.next()) {
				User user = new User();
				user.setUserName(rs.getString(1));
				list.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(connection, pstmt, rs);
		}
		return list;
	}

	@Override
	public List<User> getUsersForLogin(String loginName, String password) {
		String sql="select userName from easybuy_user where loginName=? and password=?";
		ResultSet rs=this.exxcuteQuery(sql, loginName,password);
		List<User> list=new ArrayList<User>();
		try {
			while (rs.next()) {
				User user = new User();
				user.setUserName(rs.getString(1));
				list.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			closeAll(connection, pstmt, rs);
		}
		return list;
	
	}

	@Override
	public int getTotalCount() {
		int count=-1;
		String sql="select count(1) from `easybuy_user` ";
		ResultSet rs=this.exxcuteQuery(sql);
		try {
			while (rs.next()) {
			count=rs.getInt(1);
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			this.closeAll(connection, pstmt, rs);
		}
		return count;
	}

	@Override
	public List<User> getPageUsersList(int pageNo, int pageSize) {
		String sql= "select * from easybuy_user limit ?,? ";
		List<User> list =new ArrayList<User>();
		ResultSet rs =this.exxcuteQuery(sql, (pageNo-1)*pageSize,pageSize);
		try {
			while (rs.next()) {
				User user =new User();
				user.setLoginName(rs.getString("loginName"));
				user.setUserName(rs.getString("userName"));
				user.setSex(rs.getInt("sex"));
				user.setType(rs.getInt("type"));
				list.add(user);
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			this.closeAll(connection, pstmt, rs);
		}
		return list;
	}
	

}
